package com.example.springboot.controller.uploadFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 表单上传文件测试
 * ① 请求进来使用文件上传解析器判断封装文件上传请求（MultipartResolver.isMultipart()判断是否是文件上传上传请求）
 * ② 封装返回MultipartHttpRequest
 * ③ 将request中的信息封装成map，key为上传名，value为multipartFile
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/27 15:30
 */
@Slf4j
@RestController
@Api("上传文件")
@RequestMapping("/czk")
public class UploadFileController {
    @PostMapping("/uploadFile")
    @ApiOperation("上传文件")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        log.info("【上传信息：email{},username{},headerImg{},photos{}】", email, username, headerImg.getSize(), photos.length);
        if (!headerImg.isEmpty()) {
            // 不为空
            String filename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("D:\\cache\\" + filename));
        }
        if (photos.length > 0) {
            for (MultipartFile multipartFile : photos) {
                String filename = multipartFile.getOriginalFilename();
                headerImg.transferTo(new File("D:\\cache\\" + filename));
            }
        }
        return "上传成功";
    }
}
